﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace LPLib
{
    /// <summary>
    /// Wraps the unmanaged DLL for Clustal omega
    /// </summary>
    public static class ClustalWrapper
    {
        [DllImport("clustalo.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
        private static extern int run_clustalo(string options, string input_data, StringBuilder align_output, int align_buf_len);

        /// <summary>
        /// Runs clustal omega multiple sequence alignment.
        /// </summary>
        /// <param name="pc">PolynucleotideCollection to be aligned.</param>
        /// <returns>The aligned PolynucleotideCollection</returns>
        public static PolymerCollection<byte> RunClustalOmega(PolymerCollection<byte> pc)
        {
            MixedNucleotideByte encoding = new MixedNucleotideByte();
            string inputSequences = Writer<byte>.WriteFasta(encoding, pc);
            int capacity = pc.Count * inputSequences.Length;
            StringBuilder a = new StringBuilder(capacity);
            run_clustalo(null, inputSequences, a, a.Capacity);
            PolymerCollection<byte> aligned;
            try
            {
                aligned = new PolymerCollection<byte>(encoding, a.ToString(), SequenceFileFormat.FASTA);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            aligned.Name = pc.Name;
            return aligned;
        }
    }
}
